﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using OgilvyOne.Model;
using OgilvyOne.IDAL;
using OgilvyOne.Utility;
using OgilvyOne.DALFactory;
using OgilvyOne.CommonToolLibrary.Xml;

using System.Configuration;
using OgilvyOne.Model.vico.ccc_interface;

namespace OgilvyOne.BLL
{
    public class VicoRegInfoBll
    {
        public int Add(VicoRegInfoModel model)
        {
            int i = VicoRegInfoFactory.create().Add(model);
            model.Id = i;
            if (i > 0)
            {
                try
                {
                   string strSwitch= GetConfigServ().AppSettings.Settings["switch"].Value;
                   
                   string [] campaignList=GetConfigServ().AppSettings.Settings["campaign"].Value.Split(':');
                    
                    //1:打开发送arvato接口 0:关闭发送arvato接口
                   if (strSwitch.Trim() == "1")
                   {
                       if (!ContainsCamName(model.Camname, campaignList))
                       {
                           PushDataToCCC(model);
                       }
                   }
                   
                }
                catch
                {

                }

            }
            return i;
        }
        private bool ContainsCamName(string camname,string [] camNameList)
        {
            bool isContains = false;
            
            foreach (string  campaignName in camNameList)
            {
                if (camname.Trim().ToUpper() == campaignName.ToUpper())
                {
                    isContains = true;
                    break;
                }
               
            }
            return isContains;

        }

        public bool IsExists(string email)
        {
            return VicoRegInfoFactory.create().IsExists(email);
        }
        public PageTools Query(VicoRegInfoModel q, int pagenum, int pagesize)
        {
            return VicoRegInfoFactory.create().Query(q, pagenum, pagesize);
        }
        public bool Del(string ids)
        {
            return VicoRegInfoFactory.create().Del(ids);
        }

        public VicoRegInfoModel GetModel(int id)
        {
            return VicoRegInfoFactory.create().GetModel(id);
        }

        public DataSet QueryImp(VicoRegInfoModel q)
        {
            return VicoRegInfoFactory.create().QueryImp(q);
        }

        #region CCC 接口联调

       
        private  Configuration GetConfigServ()
        {
           // string exePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "OgilvyOne.BLL.dll.config");
            string exePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.RelativeSearchPath, "OgilvyOne.BLL.dll.config");
            
            ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
            configFile.ExeConfigFilename = exePath;
            Configuration configServ = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
            return configServ;
        }

        ///// <summary>
        ///// 获取最大ID
        ///// </summary>
        ///// <returns></returns>
        //public int GetMaxID()
        //{
        //    return VicoRegInfoFactory.create().GetMaxID();
        //}

        /// <summary>
        /// 返回注册日期
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetAddTime(int id)
        {
            return VicoRegInfoFactory.create().GetAddTime(id);

        }

        /// <summary>
        /// CCC 接口联调
        /// </summary>
        /// <param name="model"></param>
        private void PushDataToCCC(VicoRegInfoModel model)
        {
            record rec = new record();
            try
            {
                string dataXML = string.Empty;
                //int id = GetMaxID();
                //model.Id = id;
                VW_CCC_Interface.RetrunInfoBean returnInfo = new OgilvyOne.BLL.VW_CCC_Interface.RetrunInfoBean();
                int recordNum = 1;
                VW_CCC_Interface.VWWebInterface vw_ccc_services = new OgilvyOne.BLL.VW_CCC_Interface.VWWebInterface();
                VW vw = new VW();
                WEBSiteInterface siteInterface = new WEBSiteInterface();
                RegisteredData regData = new RegisteredData();

                rec = SetRecord(model);
                regData.record.Add(rec);

                siteInterface.RegisteredData = regData;
                vw.WEBSiteInterface = siteInterface;
                dataXML = Serializer.XmlSerializerToText(vw);
                //dataXML = GetDataXML(model);
                VW_CCC_Interface.VWWebInterface temp = new OgilvyOne.BLL.VW_CCC_Interface.VWWebInterface();
                rec.PushTime = DateTime.Now;
                returnInfo = vw_ccc_services.pushData(dataXML, recordNum, true);
                rec.ReceiveTime = DateTime.Now;
                int resultCode = returnInfo.resultCode;
                string resultDesc = returnInfo.resultDesc;
                string resultDetail = returnInfo.resultDetail;
                rec.ResultCode = resultCode;
                rec.ResultDesc = resultDesc;
                rec.ResultDetail = resultDetail;

                int ii = UpdateReceive_CCC_Time(model.Id, DateTime.Now);
                int i = UpdateSendFlag(model.Id, resultCode.ToString(), resultDesc, resultDetail);

            }
            catch (Exception ex)
            {
                //由于avato webservice原因或网络原因导致错误写入vico_send_errorDesc字段
                rec.SendErrorDesc = ex.Message;
                rec.ReceiveTime = DateTime.Now;
                rec.ResultCode = -1;
                rec.ResultDesc = "";
                rec.ResultDetail = "";
                int iii = UpdateSendError(model.Id, ex.Message);

            }
            finally
            {
                //int icode = VicoRegInfoFactory.create().InsertToTransferDetail(rec);
                //if (icode > 0)
                {
                    //插入成功
                }  
            }
          


        }
        /// <summary>
        /// CCC接口返回状态标识更新,包括resultCode、resultDes、resultDetail
        /// </summary>
        /// <param name="id"></param>
        /// <param name="resultCode"></param>
        /// <param name="resultDesc"></param>
        /// <param name="resultDetail"></param>
        /// <returns></returns>
        private int UpdateSendFlag(int id, string resultCode, string resultDesc, string resultDetail)
        {
            return VicoRegInfoFactory.create().UpdateSendResultStatus(id, resultCode, resultDesc, resultDetail);

        }

        /// <summary>
        /// 更新返回错误状态信息，如avato webservices不可用，或网络原因造成的错误
        /// </summary>
        /// <param name="id"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private int UpdateSendError(int id, string errMsg)
        {
            return VicoRegInfoFactory.create().UpdateSendError(id, errMsg);

        }

        /// <summary>
        /// 更新avato webservice 返回状态信息时间
        /// </summary>
        /// <param name="id"></param>
        /// <param name="receiviTime"></param>
        /// <returns></returns>
        private int UpdateReceive_CCC_Time(int id, DateTime receiviTime)
        {
            return VicoRegInfoFactory.create().UpdateReceive_CCC_Time(id, receiviTime);

        }


        private string GetDataXML(VicoRegInfoModel model)
        {
            string dataXml = string.Empty;
            VW vw = new VW();
            WEBSiteInterface siteInterface = new WEBSiteInterface();
            RegisteredData regData = new RegisteredData();
            //经销商省份代码
            string dealerProvinceId = model.Dealer_provice.ToString();
            //经销商城市代码
            string dealerCityId = model.Dealer_city.ToString();
            //经销商ID
            string dealerId = model.Dealer.ToString();
            string source=string.Empty;

            //省份ID
            int provinceId = model.Province;
            //城市ID
            int cityId = model.City;


            record record = new record();
            record.recordID = model.Id;

            record.customerName = model.User_name;
            if (model.Sex.Trim().ToUpper() == "F" || (model.Sex.Trim() == "0"))
            {
                model.Sex = "女士";
            }
            else if (model.Sex.Trim().ToUpper() == "M" || (model.Sex.Trim() == "1"))
            {
                model.Sex = "先生";
            }   
            record.title = model.Sex;
            record.birthday = string.Empty;
            record.mobile = model.Mobile;
            record.secondMobile = string.Empty;
            record.phone = model.Phone;
            record.email = model.Email;
            record.address = model.Address;
            record.postCode = model.Postcode;
            record.province = VicoDealerBll.GetDealerProvince(provinceId.ToString());
            record.city = VicoDealerBll.GetDealerCity(provinceId.ToString(), cityId.ToString());
            record.district = string.Empty;
            record.isProductManuals = model.Is_product_manuals.ToString();
            record.vicoBrand = "VW轿车";

            record.vicoSeries = model.Vico_model.Trim();
            //正确调用
            record.vicoModel = string.Empty;
            //用于测试
            //record.vicoModel = model.Vico_model.Trim();
            record.vicoBuyTime = model.Vico_buy_time.Trim();
            record.vicoBuyDetailTime = string.Empty;
            record.vicoBuyBudget = model.Vico_buy_budget;
            record.vicoBuyDetailBudget = string.Empty;

            record.isIncept = model.Isincept.ToString();
           

            if(!string.IsNullOrEmpty(model.Sourec))
            {
                //source= VicoRegInfoFactory.create().GetSource(model.Sourec);
                //数据子来源
                record.sourceSub = model.Sourec;
            }
            else if(!string.IsNullOrEmpty(model.Channel))  //channel不为空 source为空
            {
                //source=VicoRegInfoFactory.create().GetSource(model.Channel);
                //数据子来源
                record.sourceSub = model.Channel;
                if (string.IsNullOrEmpty(source))
                {
                    //渠道来源                  
                    record.channelSource = model.Channel;
                }
               
            }
            
            //数据来源
            record.source =source;

            //渠道子来源目前为预留字段
            record.channelSourceSub = string.Empty;

            record.isHavaCar = model.Iscar.ToString();


            record.carBuyTime = model.Car_buy_time;
            record.brand = "VW轿车";
            //record.series = model.Vico_model.Trim();
            record.series = string.Empty;
            record.model = model.Car_brand_model;
            record.testModels = string.Empty;
            record.firstDate = string.Empty;
            record.tenDate = string.Empty;
            record.vipCardNo = string.Empty;

            record.dealerName = VicoDealerBll.GetDealerName(dealerId);
            record.dealerProvince = VicoDealerBll.GetDealerProvince(dealerProvinceId);
            record.dealerCity = VicoDealerBll.GetDealerCity(dealerProvinceId, dealerCityId);


            record.isMobile = string.Empty;
            record.isEmail = string.Empty;

            record.camName = model.Camname;
            record.addTime = GetAddTime(record.recordID);
            record.infoType = model.Info_type.ToString();

            regData.record.Add(record);

            siteInterface.RegisteredData = regData;
            vw.WEBSiteInterface = siteInterface;
            dataXml = Serializer.XmlSerializerToText(vw);
            return dataXml;
        }


        private record SetRecord(VicoRegInfoModel model)
        {
            return null;
          
            ////经销商省份代码
            //string dealerProvinceId = model.Dealer_provice.ToString();
            ////经销商城市代码
            //string dealerCityId = model.Dealer_city.ToString();
            ////经销商ID
            //string dealerId = model.Dealer.ToString();
            //string source = string.Empty;
            //string sourceSub = string.Empty;

            ////省份ID
            //int provinceId = model.Province;
            ////城市ID
            //int cityId = model.City;


            //record record = new record();
            //record.recordID = model.Id;

            //record.customerName = model.User_name;
            //if (model.Sex.Trim().ToUpper() == "F" || (model.Sex.Trim() == "0"))
            //{
            //    model.Sex = "女士";
            //}
            //else if (model.Sex.Trim().ToUpper() == "M" || (model.Sex.Trim() == "1"))
            //{
            //    model.Sex = "先生";
            //}
            //if (model.Sex.Trim() == "无")
            //{
            //    model.Sex = "";
            //}
            //record.title = model.Sex;
            //record.birthday = string.Empty;
            //record.mobile = model.Mobile;
            //record.secondMobile = string.Empty;
            //record.phone = model.Phone;
            //if(model.Email.Trim()=="无")
            //{
            //    model.Email="";
            //}
            //record.email = model.Email;
            //record.address = model.Address;
            //record.postCode = model.Postcode;
            //record.province = VicoDealerBll.GetDealerProvince(provinceId.ToString());
            //record.city = VicoDealerBll.GetDealerCity(provinceId.ToString(), cityId.ToString());
            //record.district = string.Empty;
            //record.isProductManuals = model.Is_product_manuals.ToString();
            //record.vicoBrand = "VW轿车";

            //record.vicoSeries = model.Vico_model.Trim();
            ////正确调用
            //record.vicoModel = string.Empty;
            ////用于测试
            ////record.vicoModel = model.Vico_model.Trim();
            //record.vicoBuyTime = model.Vico_buy_time.Trim();
            //record.vicoBuyDetailTime = string.Empty;
            //record.vicoBuyBudget = model.Vico_buy_budget;
            //record.vicoBuyDetailBudget = string.Empty;

            //record.isIncept = model.Isincept.ToString();

            ////活动名称不为空：campaign site
            //if (!string.IsNullOrEmpty(model.Camname))
            //{
            //    if (!string.IsNullOrEmpty(model.Sourec))
            //    {
            //        source = VicoRegInfoFactory.create().GetSource(model.Sourec);
            //        //数据子来源
            //        record.sourceSub = model.Sourec;
            //        record.channelSource = model.Channel;
            //    }
            //    else if (!string.IsNullOrEmpty(model.Channel))  //channel不为空 source为空
            //    {
            //        source = VicoRegInfoFactory.create().GetSource(model.Channel);
            //        //数据子来源
            //        record.sourceSub = model.Channel;
            //        if (string.IsNullOrEmpty(source))
            //        {
            //            //渠道来源                  
            //            record.channelSource = model.Channel;
            //        }

            //    }
            //    else
            //    {
            //        source = "campaign_site";
            //        record.channelSource = string.Empty;
            //    }

            //    //数据来源
            //    record.source = source;
            //}
            //else //活动名称为空：brand site或叫vico site
            //{
            //    //source为空
            //    if (string.IsNullOrEmpty(model.Sourec.Trim()))
            //    {
            //        //channel为空
            //        if (string.IsNullOrEmpty(model.Channel.Trim()))
            //        {
            //            source = string.Empty;
            //            sourceSub = string.Empty;
            //        }
            //        else //channel不为空
            //        {
            //            if (model.Channel.Trim().ToUpper().Contains("EDM"))
            //            {
            //                source = "eDM";
            //                sourceSub = model.Channel;
            //            }
            //        }
            //        record.source = source;
            //        record.sourceSub = sourceSub;
            //    }
            //    else
            //    {
            //        source = VicoRegInfoFactory.create().GetSource(model.Sourec.Trim());
            //        if (!string.IsNullOrEmpty(source))
            //        {
            //            if (source.ToUpper().Trim() == "CAMPAIGN_SITE")
            //            {
            //                source = "Media";
            //            }
            //            if (source.ToUpper().Trim() == "MEDIA_API")
            //            {
            //                source = "Media_API";
            //            }
            //            if (source.ToUpper().Trim() == "EDM")
            //            {
            //                source = "eDM";
            //            }
            //            if (string.IsNullOrEmpty(model.Channel))
            //            {
            //                sourceSub = string.Empty;
            //            }
            //            else
            //            {
            //                sourceSub = model.Channel;
            //            }
            //        }
            //        else
            //        {
            //            if (model.Sourec.ToUpper().Trim().Contains("EDM"))
            //            {
            //                source = "eDM";
            //                if (string.IsNullOrEmpty(model.Channel))
            //                {
            //                    sourceSub = source;   
            //                }
            //                else
            //                {
            //                    sourceSub = model.Channel;       
            //                }
            //            }
            //        }

            //        record.source = source;
            //        record.sourceSub = sourceSub;
            //    }
            //}

           

           
            ////渠道子来源目前为预留字段
            //record.channelSourceSub = string.Empty;

            //record.isHavaCar = model.Iscar.ToString();


            //record.carBuyTime = model.Car_buy_time;
            //record.brand = "VW轿车";
            ////record.series = model.Vico_model.Trim();
            //record.series = string.Empty;
            //record.model = model.Car_brand_model;
            //record.testModels = string.Empty;
            //record.firstDate = string.Empty;
            //record.tenDate = string.Empty;
            //record.vipCardNo = string.Empty;

            //record.dealerName = VicoDealerBll.GetDealerName(dealerId);
            //record.dealerProvince = VicoDealerBll.GetDealerProvince(dealerProvinceId);
            //record.dealerCity = VicoDealerBll.GetDealerCity(dealerProvinceId, dealerCityId);


            //record.isMobile = string.Empty;
            //record.isEmail = string.Empty;

            //record.camName = model.Camname;
            //record.addTime = GetAddTime(record.recordID);
            //record.infoType = model.Info_type.ToString();
            //record.transferTotal = string.Empty;
            //record.transferNumericalTime = string.Empty;
            //return record;
        }

       
        #endregion
    }
}
